package com.turing.post.datatranferpmbs.impl;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.common.util.ContrastDao;
import com.turing.post.datatranferpmbs.util.SortInfoTranferBusiness;
import com.turing.post.report.util.IncomeDaySettlement;
import com.turing.post.report.util.IncomeDaySettlementDao;
import com.turing.post.report.util.MerchantBusinessDaySettlement;
import com.turing.post.report.util.MerchantBusinessDaySettlementDao;
import com.turing.post.report.util.MerchantDaySettlement;
import com.turing.post.report.util.MerchantDaySettlementDao;
import com.turing.post.util.PCPSApplicationException;

@Stateless(mappedName = "datatranferpmbs.impl.SortInfoTranferBusinessImpl")
@Remote
@Local
public class SortInfoTranferBusinessImpl implements SortInfoTranferBusiness {

	/**
	 * 实体管理器
	 */
	@PersistenceContext
	protected EntityManager _em;
	
	@EJB(mappedName = "report.impl.MerchantDaySettlementDaoImpl")
	private MerchantDaySettlementDao MerchantDaySettlementDaoImpl;
	
	@EJB(mappedName = "report.impl.IncomeDaySettlementDaoImpl")
	private IncomeDaySettlementDao IncomeDaySettlementDaoImpl;
	
	@EJB(mappedName = "report.impl.MerchantBusinessDaySettlementDaoImpl")
	private MerchantBusinessDaySettlementDao MerchantBusinessDaySettlementDaoImpl;
	
	@EJB(mappedName = "common.impl.ContrastDaoImpl")
	private ContrastDao ContrastDaoImpl;
	
	public Date getSortTranferDate()
	{		
		return ContrastDaoImpl.getSortInfoDate();
	}
	
	public int getdaycount()
	{
		Date d=ContrastDaoImpl.getSortInfoDate();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String s=formatter.format(d);
//		System.out.println(s);
		String sql="select max(startdate)-to_date('"+s+"','yyyy-mm-dd') from Q_MCHCOST_SETTLEMENT";
		Query query = _em.createNativeQuery(sql);	
		return Integer.parseInt(query.getSingleResult().toString());
	}
	
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	@SuppressWarnings("unchecked")
	@Override
	public void transferPMBSSortInfo(Date date,String issuecompanyno)
			throws PCPSApplicationException {
		//得到新老数据库merchantno对应的Map
		HashMap<String,String> MapMerchant=ContrastDaoImpl.getMapMerchant();
		//得到新老数据库salebranchno对应的Map
		HashMap<String,String> salebranch=ContrastDaoImpl.getMapSaleBranch();
		//根据日期，取老数据库商户结算信息并循环导入
		String mersql="select m.merchantno,m.startdate,m.cost,m.count,m.turnover from Q_MCHCOST_SETTLEMENT m where startdate=?1";
		Query query = _em.createNativeQuery(mersql);
		query.setParameter(1, date);
		List<Object[]> MSDlist=query.getResultList();		
//		System.out.println(date+"老数据记录"+MSDlist.size());
		for(Object[] o:MSDlist)
		{
			MerchantDaySettlement mds=new MerchantDaySettlement();
			mds.setMerchantNo(MapMerchant.get(o[0].toString()));
			mds.setIssueCompanyNo(issuecompanyno);
			mds.setTranDate((Date)o[1]);
			mds.setConsume(new BigInteger(o[4].toString()));
			mds.setConsumeCount(new BigInteger(o[3].toString()));
			mds.setDeposit(BigInteger.ZERO);
			mds.setDepositCount(BigInteger.ZERO);
			mds.setCancelPaid(BigInteger.ZERO);
			mds.setCancelPaidCount(BigInteger.ZERO);					
			mds.setCost(new BigInteger(o[2].toString()));
			mds.setIncome(mds.getConsume().subtract(mds.getCost()));
			if(mds.getConsume().equals(BigInteger.ZERO))
				mds.setSettRatio(BigInteger.ZERO);
			else
				mds.setSettRatio(mds.getIncome().divide(mds.getConsume()));		
			mds.setPastIncome(BigInteger.ZERO);
			mds.setPaidFund(mds.getCost());
			mds.setFee(BigInteger.ZERO);
			mds.setIssueFund(BigInteger.ZERO);			
			
			if(mds.getSettRatio().intValue()>=10000)
				mds.setSettRatio(new BigInteger("9999"));
			
			MerchantDaySettlementDaoImpl.insert(mds);
			
		}
		
		//根据日期，取老数据库销售机构分成信息并循环导入
		
		//取老数据sql
		String salesql="select m.merchantno,m.sortingdate,m.customid,nvl(sum(m.cardamount),0),m.rate*10000,nvl(sum(m.revenue),0)  from q_income_sorting_mi m "+
				"where m.sortingdate=?1 "+
				"group by m.merchantno,m.sortingdate,m.customid,m.rate "+
				"union  "+
				"select p.merchantno,p.trandate,p.customid,nvl(sum(p.sales),0),p.rate*10000,nvl(sum(p.revenue),0) from income_sorting_poss p "+
				"where p.trandate=?1 "+
				"group by p.merchantno,p.trandate,p.customid,p.rate";
		Query squery = _em.createNativeQuery(salesql);
		squery.setParameter(1, date);
		List<Object[]> idslist=squery.getResultList();		
//		System.out.println(date+"老数据记录iii"+idslist.size());
		for(Object[] o:idslist)
		{
			IncomeDaySettlement ids=new IncomeDaySettlement();
			ids.setIssueCompanyNo(issuecompanyno);
			ids.setMerchantNo(MapMerchant.get(o[0].toString()));
			ids.setTranDate((Date)o[1]);
			ids.setSaleBranchNo(salebranch.get(o[2].toString()));
			ids.setMIncomeBranchId(new BigInteger("0"));
			ids.setSIncomeBranchId(new BigInteger("0"));
			ids.setConsume(new BigInteger(o[3].toString()));
			ids.setDeposit(BigInteger.ZERO);
			ids.setSettRatio(new BigInteger(o[4].toString()));
			ids.setSIncome(new BigInteger(o[5].toString()));
			ids.setMIncome(BigInteger.ZERO);
			ids.setSPastIncome(BigInteger.ZERO);
			ids.setMPastIncome(BigInteger.ZERO);
			if(ids.getSettRatio().intValue()>=10000)
				ids.setSettRatio(new BigInteger("9999"));
			IncomeDaySettlementDaoImpl.insert(ids);
			
		}
		
		//取米旗老数据sql
		String mi_salesql="select m.merchantno,m.startdate,m.cost,m.count,m.turnover,(select nvl(sum(cashamount),0) from q_income_sorting_mi where merchantno='0001' and sortingdate=?1) "+
							"from Q_MCHCOST_SETTLEMENT m where startdate=?1 and merchantno='0001'";
		Query misquery = _em.createNativeQuery(mi_salesql);
		misquery.setParameter(1, date);
		List<Object[]> mislist=misquery.getResultList();			
		for(Object[] o:mislist)
		{
			MerchantBusinessDaySettlement mbds=new MerchantBusinessDaySettlement();
			mbds.setMerchantNo(MapMerchant.get(o[0].toString()));
			mbds.setIssueCompanyNo(issuecompanyno);
			mbds.setTranDate((Date)o[1]);
			mbds.setBusinessType("01");
			mbds.setConsume(new BigInteger(o[4].toString()));
			mbds.setCancelPaid(BigInteger.ZERO);
			mbds.setCost(new BigInteger(o[2].toString()));
			mbds.setIncome(mbds.getConsume().subtract(mbds.getCost()));
			if(mbds.getConsume().equals(BigInteger.ZERO))
				mbds.setSettRatio(BigInteger.ZERO);
			else
				mbds.setSettRatio(mbds.getIncome().divide(mbds.getConsume()));	
			mbds.setOtherPaid(new BigInteger(o[5].toString()));
			
			if(mbds.getSettRatio().intValue()>=10000)
				mbds.setSettRatio(new BigInteger("9999"));
		
			MerchantBusinessDaySettlementDaoImpl.insert(mbds);
			
		}
		ContrastDaoImpl.updateSortInfoDate(date);
//		System.out.println("更新日期成功");
	}

}
